﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for PublisherView.xaml
    /// </summary>
    public partial class PublisherView
    {
        private readonly PublisherController _publisherControl;
        private IList<Publisher> _publishers;

        public PublisherView()
        {
            InitializeComponent();

            _publisherControl = new PublisherController();
            _publishers = _publisherControl.GetAllPublisher();
            dataGridPublisher.ItemsSource = _publishers;
        }

        private void RefreshGrid()
        {
            dataGridPublisher.ItemsSource = null;
            _publishers = _publisherControl.GetAllPublisher();
            dataGridPublisher.ItemsSource = _publishers;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new PublisherEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridPublisher.SelectedItem == null)
                    throw new NullReferenceException();

                var publisher = _publishers
                        .Where(p => p.Id == _publishers[dataGridPublisher.SelectedIndex].Id)
                        .Select(p => p)
                        .Single();

                _publisherControl.DeletePublisher(publisher);
                MessageBox.Show("sukses menghapus publisher");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridPublisher.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new PublisherEditorView(_publishers[dataGridPublisher.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
